#  ads 和 rms之间的业务api

import json
import traceback
from httpx_client import HttpXClient, RespFmt
import asyncio


class RmsApiX:

    def __init__(self):
        self.httpx_client = HttpXClient()
        self.base_url = "http://devrms.ywx.com/api"
        self.pad_authorization = "67fe4fb5-f823-11ec-a9c1-bc5ff4da923c"
        self.device_authorization = "72fc6dc2999a9d1f5cc316d82bff7edb"

    async def load_line_config_by_token(self , line_token ):
        """ 根据产线token ， 获取产线信息 """
        try:
            headers = dict(aiAuthorization=line_token)
            url = self.base_url + "/ai/device/deviceQueryProLineInfo"
            response = await self.httpx_client.get(url=url, headers=headers)
            return response['data']
        except:
            err = traceback.format_exc()
            print(f"-------load_line_config_by_token:{err}")
            return None

    async def get_bind_qrcode(self):
        """ 获取绑定的二维码信息 """
        try:
            headers = dict(PadAuthorization = self.pad_authorization , DeviceAuthorization = self.device_authorization )
            url = self.base_url + "/device/deviceBinding/getBindingQrCode"
            response = await self.httpx_client.get(url=url, headers=headers)
            data = response["data"]
            qr_content = data["content"]
            return qr_content
        except:
            err = traceback.format_exc()
            print(f"-------reportTimeNew:{err}")

    async def report_device_info(self , qr_content , device_no):
        try:
            device_config_reported = dict(deviceId=f"{device_no}")
            data = dict(qrCodeContent=qr_content, deviceNo=device_no, deviceType=4, deviceConfig=json.dumps(device_config_reported), deviceVersionCode=83)
            headers = dict(PadAuthorization=self.pad_authorization, DeviceAuthorization=self.device_authorization)
            url = self.base_url + "/device/deviceBinding/qrCodeBindingData"
            response = await self.httpx_client.post(url=url, headers=headers, data=data)
            return response['msg']
        except:
            err = traceback.format_exc()
            print(f"-------reportTimeNew:{err}")


    async def bind_device(self, login_token, qr_content, device):
        """  绑定设备 """
        try:
            device_id = device["qualitylocationId"]
            machineLocationRelId = device["machineLocationRelId"]
            proLineId = device["proLineId"]
            headers = dict(
                Authorization=login_token,
                Timezone="Asia/Shanghai"
            )
            data = dict(qrCodeContent=qr_content, proLineId=str(proLineId) , machineLocationRelId=machineLocationRelId)
            url = self.base_url + "/erp/deviceInfo/binding"
            response = await self.httpx_client.post(url=url, headers=headers, data=data, resp_fmt = RespFmt.JSON)
            print(f"-------bind_device:{device_id}, {response}, msg:{response['msg']}")
            return response['msg']
        except:
            err = traceback.format_exc()
            print(f"-------load_factory_config:{err}")
            return None


    async def bind_device_new(self, login_token, device_no, device):
        """  绑定设备 """
        try:
            device_id = device["qualitylocationId"]
            machineLocationRelId = device["machineLocationRelId"]
            proLineId = device["proLineId"]
            headers = dict(
                Authorization=login_token,
                Timezone="Asia/Shanghai"
            )
            data = dict(deviceNo=device_no, proLineId=str(proLineId) , machineLocationRelId=machineLocationRelId)
            url = self.base_url + "/erp/aiDevice/binding"
            response = await self.httpx_client.post(url=url, headers=headers, data=data, resp_fmt = RespFmt.JSON)
            print(f"-------bind_device:{device_id}, {response}, msg:{response['msg']}")
            return response['msg']
        except:
            err = traceback.format_exc()
            print(f"-------load_factory_config:{err}")
            return None

    async def get_lines(self, admin_login_token, factory_id, line_id):
        """ 获取工厂所有产线信息 """
        try:
            headers = dict(Authorization = admin_login_token )
            params = dict(pageNum=1, pageSize=10, factoryId=factory_id, proLineId=line_id)
            url = self.base_url + "/erp/aiMachineLocation/list"
            response = await self.httpx_client.get(url=url, headers=headers, params=params)
            data = response["rows"]
            return data
        except:
            err = traceback.format_exc()
            print(f"-------reportTimeNew:{err}")

    async def get_model_position_info(self, admin_login_token, location_rel_id):
        """ 获取模版中机位信息 """
        try:
            headers = dict(Authorization = admin_login_token )
            params = dict(machineLocationRelId=location_rel_id)
            url = self.base_url + "/erp/aiMachineLocationRel/queryConfigAndErrorList"
            response = await self.httpx_client.get(url=url, headers=headers, params=params)
            data = response["data"]
            return data
        except:
            err = traceback.format_exc()
            print(f"-------reportTimeNew:{err}")


    async def init_default_config(self, admin_login_token, location_rel_id, config_json_str:str):
        """ 初始化默认机位配置信息 """
        try:
            headers = dict(Authorization=admin_login_token)
            data = dict(machineLocationRelId=location_rel_id, configJson=config_json_str)
            url = self.base_url + "/erp/aiMachineLocationRel/editMachineLocationRelConfig"
            response = await self.httpx_client.post(url=url, headers=headers, data=data, resp_fmt = RespFmt.JSON)
            code = response["code"]
            return code == 200
        except:
            err = traceback.format_exc()
            print(f"-------init_default_config:{err}")
            return False